<template>
    <div style="height: 5%;display: flex;">
        <div  >
            &nbsp; &nbsp;
            <n-button strong secondary @click="back()" text type="primary">
                <jb-icon :local="true" icon="ri:arrow-left-double-fill" height="30"></jb-icon> &nbsp;&nbsp; 返回
            </n-button>
        </div>
    </div>
    <jb-crud-page ref="pageRef" :searchUrl="pageUrl" :conditions-align="'start'" :searchConditions="pageConditions"
                  :editComponent="Edit" @afterSearch="handleAfterSearch" @afterRender="handleAfterRender" style="height: 90%">
        <template #conditions-form>
            <jb-input v-model:value="pageConditions.keywords" placeholder="请输入名称" clearable/>
        </template>
        <template #default="{list,tableStartIndex}">
            <n-layout has-sider>
                <n-layout>
                    <jb-table v-if="showTable" ref="tableRef" :row-config="{keyField: 'id', isHover: true}"
                              :checkbox-config="{ trigger: 'row',checkRowKeys:selectList.map(item=>item.id) }"
                              @checkbox-all="selectAllChangeEvent" @checkbox-change="selectChangeEvent" :data="list"
                              :start-index="tableStartIndex" showOverflow="tooltip">
                        <jb-column type="checkbox" width="60" fixed="left"></jb-column>
                        <jb-column type="seq" title="序号" width="60" fixed="left"></jb-column>
                        <jb-column field="sn" title="编号" min-width="160" fixed="left"></jb-column>
                        <jb-column field="briefInfo" title="Function描述" min-width="200"></jb-column>
                        <jb-column field="serviceMethod" title="Service方法" min-width="100"></jb-column>
                    </jb-table>
                </n-layout>

            </n-layout>
        </template>
    </jb-crud-page>
    <div class="flex justify-center" style="height: 5%;align-items: end;">
        <jb-btn type="primary" @click="submit">提交-挂载Function Call</jb-btn>
    </div>
</template>

<script setup>
import {
    useResetableData
} from "@/hooks/common/use-resetable-data.js";
import Edit from "../../../../param-management/cpns/edit.vue"
import {
    onMounted,
    ref
} from "vue";
import {
    JBoltApi
} from "@/service/request/index.js";
import {useMessage} from 'naive-ui'

const message = useMessage()
const emits = defineEmits(['closeFunction'])

const props = defineProps({
    appId: String
})

const pageRef = ref(null)
const pageUrl = ref('')
const pageConditions = useResetableData({
    keywords: '',
    enabled: true
})

const tableRef = ref(null)

const selectList = ref([])
function back() {
    emits('closeFunction')
}

// 单选事件处理
function selectChangeEvent({
                               row,
                               checked
                           }) {
    if (checked) {
        if (!selectList.value.some(item => item.id === row.id)) {
            selectList.value.push(row);
        }
    } else {
        selectList.value = selectList.value.filter(item => item.id !== row.id);
    }
}

const selectAllChangeEvent = ({
                                  checked
                              }) => {
    const $table = tableRef.value;
    if ($table) {
        const records = $table.getCheckboxRecords();
        if (checked) {
            // 全选时，将所有记录添加到 selectList 中，并去重
            const existingIds = new Set(selectList.value.map(item => item.id));
            const newRecords = records.filter(record => !existingIds.has(record.id));
            selectList.value = [...selectList.value, ...newRecords];
        } else {
            // 反选时，移除所有记录
            const recordIds = new Set(resultList.value.map(record => record.id));
            selectList.value = selectList.value.filter(item => !recordIds.has(item.id));
        }
        console.log(checked ? '所有勾选事件' : '所有取消事件', records);
        console.log('手动', selectList.value);
    }
}

const resultList = ref([])

function handleAfterSearch(list) {
    resultList.value = list
}

function handleAfterRender(list) {
    const $table = tableRef.value
    if ($table) {
        $table.setCheckboxRow(selectList.value, true)
    }
}

function handleRemoveItem(item) {
    // 从选中列表中移除
    selectList.value = selectList.value.filter(i => i.id !== item.id)

    // 取消表格中对应行的选中状态
    const $table = tableRef.value
    if ($table) {
        $table.setCheckboxRow([item], false)
    }
}



//绑定functioncall
const submit = async () => {
    if (selectList.value.length > 0) {
          JBoltApi.tryPost('/aiApp/submitFunction', {
            appId: props.appId,
            list: selectList.value.map(item => item.id)
        }).then((res)=>{
            message.success('保存成功');
              emits('closeFunction');
          }).catch(error => {
              console.error(error)
          })
    }else{
        message.error('请选择Function');
    }
}

defineExpose({
    submit
})
const showTable = ref(false)

function loadSelectedList() {
    JBoltApi.tryGet('/aiApp/getFuncByAppId', {
        appId: props.appId
    }).then(res => {
        if (res.data != null) {
            selectList.value = res.data.map(item => {
                return {
                    name: item.briefInfo,
                    sn: item.sn,
                    id: item.key
                }
            })
        }
        console.log(
            selectList.value
        )
        showTable.value = true
        pageUrl.value = '/aiFunction/list'
    }).catch((error) => {
        console.error(error)
    })
}

onMounted(() => {
    if (props.appId) {
        loadSelectedList()
    }
})
</script>


<style scoped>
.selected-items-container {
    font-size: 12px;
    color: #6c7381;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.selected-header {
    padding: 8px 0;
    font-weight: 500;
    border-bottom: 1px solid var(--n-border-color);
    margin-bottom: 12px;
}

.selected-content {
    flex: 1;
    overflow-y: auto;
}

.selected-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    margin-bottom: 8px;
    border-radius: 4px;
    background-color: var(--n-card-color);
    transition: all 0.3s;
}

.selected-item:hover {
    background-color: var(--n-table-header-color);
}

.item-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 8px;
}

.delete-btn {
    opacity: 0.8;
}

.delete-btn:hover {
    opacity: 1;
}

.empty-text {
    text-align: center;
    color: var(--n-text-color-disabled);
    padding: 32px 0;
}
</style>